<template>
  <div class="datas">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="line-height: 36px;">数据管理</span>
        <el-button style="float: right;" type="primary" @click="dialogOpen('add')" v-if="USER.auth.indexOf('addDatas')!==-1">新增数据项</el-button>
      </div>
      <s-table :table="table"
               :expand="false"
               @http="tableWatch">
        <el-form-item slot="multiSelect" label="多选操作" prop="multiSelect" v-if="table.multiSelect">
          <el-row>
            <el-col :span="8">
              <el-button size="small" type="danger" @click="tableMultiDelete">多选删除</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-table-column
          fixed="right"
          slot="operation"
          align="center"
          label="可用操作"
          width="100">
          <template scope="s">
            <el-tooltip placement="top">
              <div slot="content">查看其中数据集</div>
              <el-button type="info" icon="search" size="mini" @click="dialogSearchOpen(s.row)"></el-button>
            </el-tooltip>
            <el-tooltip placement="top">
              <div slot="content">更多可用操作</div>
              <el-popover
                popper-class="demo-table-expand"
                placement="right"
                title="更多可用操作"
                trigger="click">
                <slot name="content">
                  <div>
                    <el-button type="info" icon="edit" size="mini" @click="tableEdit(s.row)" v-if="USER.auth.indexOf('modDatas')!==-1">编辑数据项</el-button>
                    <el-button type="danger" icon="delete" size="mini" @click="tableDelete(s.row)" v-if="USER.auth.indexOf('deleteDatas')!==-1">删除数据项</el-button>
                  </div>
                </slot>
                <el-button slot="reference" type="info" icon="more" :plain="true" size="mini"
                           class="__reference"></el-button>
              </el-popover>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-form-item label="数据名称" prop="name">
          <el-input type="text"
                    class="input"
                    v-model="autoVueTable_dName"
                    placeholder="数据名称" spellcheck="false" auto-capitalize="off" auto-complete="off"
                    auto-correct="off"></el-input>
        </el-form-item>
      </s-table>
    </el-card>
    <s-dialog :dialog="dialog" :close="dialogInit">
      <p slot="title">{{dialog.title}}<span>{{formDialog.id ? ('数据项编码：' + formDialog.dCode) : ''}}</span></p>
      <s-form :form="formDialog" ref="formDialog">
        <el-row>
          <el-col :xs="24" :lg="{span: 5, offset: 0}">
            <el-form-item prop="dName" label="数据项名称">
              <el-input
                type="text"
                v-model="formDialog.dName"
                placeholder="数据项名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 5, offset: 1}">
            <el-form-item prop="dType" label="数据项类型">
              <el-select v-model="formDialog.dType" placeholder="请选择">
                <el-option
                  v-for="item in DATAS.dType"
                  :key="item.dictionaryid"
                  :label="item.value"
                  :value="item.dictionaryid">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 5, offset: 1}">
            <el-form-item prop="dbType" label="数据库类型">
              <el-select v-model="formDialog.dbType" placeholder="请选择">
                <el-option
                  label="mysql"
                  value="mysql">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 5, offset: 1}">
            <el-form-item prop="dCode" label="数据项编码">
              <el-input
                type="text"
                v-model="formDialog.dCode"
                placeholder="数据项编码"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :lg="{span: 5, offset: 0}">
            <el-form-item prop="dbIp" label="数据库IP">
              <el-input
                type="text"
                v-model="formDialog.dbIp"
                placeholder="数据库IP"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 5, offset: 1}">
            <el-form-item prop="dbPort" label="数据库端口">
              <el-input
                type="text"
                v-model="formDialog.dbPort"
                placeholder="数据库端口"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 5, offset: 1}">
            <el-form-item prop="dbExample" label="数据库实例">
              <el-input
                type="text"
                v-model="formDialog.dbExample"
                placeholder="数据库实例"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 5, offset: 1}">
            <el-form-item prop="dbTable" label="数据库表名">
              <el-input
                type="text"
                v-model="formDialog.dbTable"
                placeholder="数据库表名"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :lg="{span: 5, offset: 0}">
            <el-form-item prop="dbUsername" label="数据库用户名">
              <el-input
                type="text"
                v-model="formDialog.dbUsername"
                placeholder="数据库用户名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 5, offset: 1}">
            <el-form-item prop="dbPassword" label="数据库密码">
              <el-input
                type="text"
                v-model="formDialog.dbPassword"
                placeholder="数据库密码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 5, offset: 1}">
            <el-form-item prop="dbOrderCor" label="名称字段">
              <el-input
                type="text"
                v-model="formDialog.dbOrderCor"
                placeholder="名称字段"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 5, offset: 1}">
            <el-form-item prop="dbValueCor" label="值域字段">
              <el-input
                type="text"
                v-model="formDialog.dbValueCor"
                placeholder="值域字段"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :lg="{span: 5, offset: 0}">
            <el-form-item prop="dbForeginCor" label="父字段">
              <el-input
                type="text"
                v-model="formDialog.dbForeginCor"
                placeholder="父字段"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 5, offset: 1}">
            <el-form-item prop="dbSortCor" label="排序字段">
              <el-input
                type="text"
                v-model="formDialog.dbSortCor"
                placeholder="排序字段"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 5, offset: 1}">
            <el-form-item prop="dbFilter" label="过滤条件">
              <el-input
                type="text"
                v-model="formDialog.dbFilter"
                placeholder="过滤条件"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 5, offset: 1}">
            <el-form-item prop="dPid1" label="所属应用">
              <el-select v-model="formDialog.dPid1" placeholder="请选择">
                <el-option
                  v-for="item in dialog.app"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :lg="{span: 5, offset: 0}">
            <el-form-item prop="dPid" label="父数据项">
              <el-select v-model="formDialog.dPid" placeholder="请选择">
                <el-option
                  v-for="item in dialog.dPid"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 5, offset: 1}" v-if="formDialog.dPid !== 0">
            <el-form-item prop="dbFForeginCor" label="关联字段">
              <el-input
                type="text"
                v-model="formDialog.dbFForeginCor"
                placeholder="过滤条件"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </s-form>
      <el-button slot="footer" @click="dialogSave">保存</el-button>
    </s-dialog>
    <s-dialog :dialog="dialogSearch" :close="dialogSearchInit" :closeTip="false">
      <p slot="title">{{dialogSearch.title}}<span>数据项名称：{{dialogSearch.row.dName}}</span></p>
      <s-table :table="tableSearch"
               :control="false"
               :expand="false"
               @http="tableWatch">
        <el-table-column
          fixed="right"
          slot="operation"
          align="center"
          label="可用操作"
          width="140">
          <template scope="s">
            <el-button type="info" icon="search" size="mini" @click="dialogSearchSearchOpen('WATCH', s.row)" v-if="USER.auth.indexOf('searchDataset')!==-1"></el-button>
            <el-button type="success" icon="edit" size="mini" @click="dialogSearchSearchOpen('PUT', s.row)" v-if="USER.auth.indexOf('editDataset')!==-1"></el-button>
            <el-button type="danger" icon="delete" size="mini" @click="tableSearchDelete(s.row)" v-if="USER.auth.indexOf('deleteDataset')!==-1"></el-button>
          </template>
        </el-table-column>
      </s-table>
      <el-button slot="footer" type="primary" @click="dialogSearchSearchOpen('ADD')" v-if="USER.auth.indexOf('addDataset')!==-1">添加数据集</el-button>
    </s-dialog>
    <s-dialog :dialog="dialogSearchSearch" :close="dialogSearchSearchInit" :closeTip="(formDialogSearchSearch.id == 0)">
      <p slot="title">{{dialogSearchSearch.title}}数据集<span>{{dialogSearchSearch.title !== '新增' ? ('数据集名称：' + dialogSearchSearch.row.dName) : ('数据项名称：' + dialogSearch.row.dName) }}</span></p>
      <s-form :form="formDialogSearchSearch" ref="formDialogSearchSearch">
        <template v-if="(formDialogSearchSearch.id == 0)">
          <el-form-item prop="dName"
                        label="数据集名称">
            <el-input
              type="text"
              v-model="formDialogSearchSearch.dName"
              placeholder="数据集名称"></el-input>
          </el-form-item>
          <el-form-item prop="ids" label="数据集内容">
            <span v-if="formDialogSearchSearch.id == 0">
              <el-checkbox v-show="!dialogSearchSearch.all" :indeterminate="dialogSearchSearch.isIndeterminate" v-model="dialogSearchSearch.checkAll" @change="checkAllChange">全选</el-checkbox>
              <el-checkbox v-model="dialogSearchSearch.all">不限</el-checkbox>
            </span>
            <el-tree
              v-show="!dialogSearchSearch.all"
              ref="tree0"
              :render-content="treeContent0"
              :data="dialogSearchSearch.tree.data"
              :default-checked-keys="formDialogSearchSearch.ids"
              @check-change="checkChange"
              show-checkbox
              node-key="key">
            </el-tree>
          </el-form-item>
        </template>
        <el-form-item v-else prop="ids" label="数据集内容">
          <el-tree
            ref="tree1"
            :data="dialogSearchSearch.tree.data"
            :default-checked-keys="formDialogSearchSearch.ids"
            @check-change="checkChange"
            node-key="key">
          </el-tree>
        </el-form-item>
      </s-form>
      <el-button slot="footer" type="primary" v-if="(formDialogSearchSearch.id == 0)" @click="dialogSearchSearchSave">保存</el-button>
      <el-button slot="footer" type="primary" v-if="!(formDialogSearchSearch.id == 0)" @click="dialogSearchSearchOk">好</el-button>
    </s-dialog>
  </div>
</template>

<script>
  import {AutoVue, AutoPromise} from '~/plugins/Tools';

  function __form () {
    return {
      id: {value: 0},
      dName: {value: '', rule: ['vNull']},
      dType: {value: 1, rule: ['vNull']},
      dCode: {value: '', rule: ['vNull']},
      dbType: {value: 'mysql', rule: ['vNull']},
      dbIp: {value: '', rule: ['vNull']},
      dbPort: {value: '', rule: ['vNull']},
      dbExample: {value: '', rule: ['vNull']},
      dbUsername: {value: '', rule: ['vNull']},
      dbPassword: {value: '', rule: ['vNull']},
      dbTable: {value: '', rule: ['vNull']},
      dbOrderCor: {value: '', rule: ['vNull']},
      dbValueCor: {value: '', rule: ['vNull']},
      dbForeginCor: {value: '', rule: []},
      dbSortCor: {value: '', rule: []},
      dbFilter: {value: '', rule: []},
      dPid1: {value: '', rule: ['vNull']},
      dPid: {value: 0, rule: ''},
      dbFForeginCor: {value: '', rule: ''},
    };
  }
  function __formDialogSearchSearch () {
    return {
      id: {value: 0},
      dName: {value: '', rule: ['vNull']},
      ids: {value: [], rule: []},
    };
  }

  export default AutoVue({
    transition: 'slide-fade',
    name: 'datas-safety',
    store: ['DICTIONARY_datas', 'DATAS', 'USER_user', 'USER'],
    data: {
      table: {
        column: [ { label: '数据项名', prop: 'dName', minWidth: '0px', search: true },
          { label: '数据项码', prop: 'dCode', minWidth: '0px', search: false },
          { label: '类型',
            prop: 'show_dType',
            minWidth: '0px',
            search: false },
          { label: '更新时间',
            prop: 'dUpdatetime',
            minWidth: '0px',
            formatter: (row, column) => {
              return this.a.methods.formatterTime(row[column.property || column], 1);
            },
            search: false },
        ],
        url: '/datas/',
        key: 'id',
        tableColumn: 4,
      },
      formDialog: __form(),
      formDialogSearchSearch: __formDialogSearchSearch(),
      dialog: {
        title: '新增',
        formRef: 'formDialog',
        size: 'large',
        app: [],
        dPid: [],
      },
      dialogSearch: {
        title: '查看数据项',
        row: {},
      },
      dialogSearchSearch: {
        title: '新增',
        formRef: 'formDialogSearchSearch',
        tree: {
          data: [],
          size: 0,
        },
        ids: [],
        isIndeterminate: false,
        checkAll: false,
        all: false,
        row: {},
        idsOld: [],
      },
      tableSearch: {
        column: [ { label: '数据集名称', prop: 'dName', minWidth: '0px', search: false },
          { label: '创建人', prop: 'dCreater', minWidth: '0px', search: false },
        ],
        url: '/datas/',
        key: 'id',
        tableColumn: 2,
      },
    },
    computed: {
      treeSize: function () {
        let tree = this.formDialogSearchSearch.id === 0 ? 'tree0' : 'tree1';
        let obj = Object.create(this.$refs[tree].store.nodesMap);
        let length = 0;
        for (let a in obj) {
          length++;
        }
        return length;
      },
    },
    methods: {
      treeContent0 (h, { node, data, store }) {
        return (
          <span>
            <span>
              <span>{node.label}</span>
            </span>
            <span style="float: right; margin-right: 20px">
              <el-button size="mini" type="success" class={{ 'display': (!node.data.include || node.data.disabled) }} on-click={event => this.treeChangeInclude(event, node.data)}>包含</el-button>
              <el-button size="mini" type="danger" class={{ 'display': (node.data.include || node.data.disabled) }} on-click={event => this.treeChangeInclude(event, node.data)}>不含</el-button>
            </span>
          </span>);
      },
      treeContent1 (h, { node, data, store }) {
        let _this = this;
        return (
          <span>
            <span>
              <span>{node.label}</span>
            </span>
            <span style="float: right; margin-right: 20px">
              <el-tag type="success" class={{ 'display': (!node.data.include) }}>包含</el-tag>
              <el-tag type="danger" class={{ 'display': (node.data.include) }}>不含</el-tag>
            </span>
          </span>);
      },
      treeChangeInclude (event, data) {
        if (!data.disabled && (!data.children || (data.children && data.children.length === 0))) {
          let tree = this.$refs[this.formDialogSearchSearch.id === 0 ? 'tree0' : 'tree1'];
          let keys = new Set(tree.getCheckedKeys());
          let keysLength = keys.size;
          if (!data.include) {
            keys.add(data.key);
          } else {
            keys.delete(data.key);
          }
          if (keys.size !== keysLength) {
            tree.setCheckedKeys(Array.from(keys));
          }
        }
        data.include = !data.include;
        if (event) event.stopPropagation();
      },
      tableEdit (row) {
        this.dialogOpen('PUT', row);
      },
      tableDelete (row) {
        this.$confirm('您将删除数据。', '确认删除？', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        })
          .then(async _ => {
            try {
              await this.post('/datas/delete/', [row.id]);
              this.tableWatch('table');
            } catch (err) {
              console.log(err);
            }
          })
          .catch(_ => {
          });
      },
      tableMultiDelete () {
        this.$confirm('您将删除这些数据。', '确认删除？', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        })
          .then(async _ => {
            let step = [];
            for (let item of this.table.multipleSelection) {
              step.push(item.id);
            }
            try {
              await this.post('/datas/delete/', step);
              this.tableWatch('table');
            } catch (err) {
              console.log(err);
            }
          })
          .catch(_ => {
          });
      },

      dialogInit (formRef) {
        const init = formRef => {
          switch (formRef) {
          case 'formDialog':
            obj = __form();
            break;
          case 'formDialogSearchSearch':
            obj = __formDialogSearchSearch();
            break;
          }
          this[formRef] = {
            ...this[formRef],
            ...this.ObjectClone(obj),
          };
          this.resetFields(formRef);
        };
        let obj = {};
        if (formRef && formRef.constructor === Array) {
          for (let item of formRef) {
            init(item);
          }
        } else {
          init(formRef);
        }
      },
      async dialogOpen (type, more) {
        if (type) {
          type = type.toUpperCase();
        } else return;
        await AutoPromise([
          async () => {
            if (!this.DICTIONARY_datas) {
              await this.USE('DICTIONARY_datas');
            }
          },
          async () => {
            if (this.dialog.app.length === 0) {
              this.dialog.app = await this.get('/app/getAll');
            }
          },
          async () => {
            if (this.dialog.dPid.length === 0) {
              let data = await this.get('/datas/');
              data = [{
                id: 0,
                name: '不选',
              }, ...data];
              this.dialog.dPid = data;
            }
          },
        ]);
        switch (type) {
        case 'ADD':
          this.dialog.title = '新增';
          break;
        case 'PUT':
          this.dialog.title = '修改';
          if (more.dInfo) {
            let json = JSON.parse(more.dInfo);
            more = {
              ...more,
              ...json,
            };
          }
          for (let index in this.formDialog) {
            if (this.formDialog.hasOwnProperty(index)) {
              if (typeof more[index] !== 'undefined') {
                this.formDialog[index] = more[index];
              }
            }
          }
          break;
        }
        this.dialog.visible = true;
      },
      dialogSave () {
        let formRef = 'formDialog';
        if (this.dialog.title === '新增') {
          this.VALIDATE(formRef, async option => {
            option.dAppid = option.dPid1;
            delete option.dPid1;
            if (option.dPid === 0) {
              delete option.dbFForeginCor;
            }
            try {
              let {id} = await this.post('/datas/add', option);
              option.id = id;
              this.tableWatch('table');
              this.dialogInit(formRef);
              this.dialog.visible = false;
            } catch (err) {
              console.log(err);
            }
          });
        } else {
          this.VALIDATE(formRef, async option => {
            option.dAppid = option.dPid1;
            delete option.dPid1;
            if (option.dPid === 0) {
              delete option.dbFForeginCor;
            }
            try {
              await this.post('/datas/add', option);
              this.tableWatch('table');
              /*
              for (let i = 0; i < this.table.data.length; i++) {
                if (this.table.data[i].id === option.id) {
                  for (let index in this.table.data[i]) {
                    if (this.table.data[i].hasOwnProperty(index)) {
                      this.table.data[i][index] = option[index];
                    }
                  }
                }
              }
              */
              this.dialogInit(formRef);
              this.dialog.visible = false;
            } catch (err) {
              console.log(err);
            }
          });
        }
      },

      dialogSearchInit () {
        this.dialogSearch.id = 0;
        this.tableSearch.data = [];
      },
      dialogSearchOpen (row) {
        this.dialogSearch.row = row;
        this.tableSearch.url = '/datas/' + row.id;
        this.tableWatch('tableSearch');
        this.dialogSearch.visible = true;
      },
      dialogSearchSave () {
        this.dialogSearchInit();
        this.dialogSearch.visible = false;
      },

      dialogSearchSearchInit () {
        this['formDialogSearchSearch'] = {
          ...this['formDialogSearchSearch'],
          ...this.ObjectClone(__formDialogSearchSearch()),
        };
        this.dialogSearchSearch.tree.data = [];
        this.dialogSearchSearch.tree.size = 0;
        this.dialogSearchSearch.isIndeterminate = false;
        this.dialogSearchSearch.checkAll = false;
        this.dialogSearchSearch.all = false;
        this.dialogSearchSearch.row = {};
        this.dialogSearchSearch.idsOld = [];
      },
      async dialogSearchSearchOpen (type, row) {
        if (type) {
          type = type.toUpperCase();
        } else return;
        switch (type) {
        case 'ADD':
          this.dialogSearchSearch.title = '新增';
          let {
            contentlist,
          } = await this.get('/datas/' + this.dialogSearch.row.id);
          this.dialogSearchSearch.tree.data = treeFormat(contentlist);
          console.log(this.dialogSearchSearch.tree.data);
          this.dialogSearchSearch.ids = [];
          break;
        case 'PUT':
          this.dialogSearchSearch.title = '修改';
          this.dialogSearchSearch.row = row;
          let json = await this.get('/datasetImpl/update/' + row.id);
          this.dialogSearchSearch.tree.data = treeFormat(json.contentlist, json.ids);
          this.dialogSearchSearch.all = json.all;
          this.dialogSearchSearch.ids = json.ids;
          this.dialogSearchSearch.idsOld = json.ids;
          this.formDialogSearchSearch.dName = row.dName;
          this.$nextTick(() => {
            this.dialogSearchSearch.tree.size = dialogSearchGetSize(this.dialogSearchSearch.tree.data);
            let tree = this.$refs[this.formDialogSearchSearch.id === 0 ? 'tree0' : 'tree1'];
            let stepIds = [];
            for (let key of this.dialogSearchSearch.ids) {
              if (typeof key === 'undefined') {
                continue;
              }
              if (tree.store.nodesMap[key].childNodes.length === 0) {
                stepIds.push(key);
              }
            }
            tree.setCheckedKeys(stepIds);
          });
          break;
        case 'WATCH':
          this.dialogSearchSearch.title = '查看';
          this.dialogSearchSearch.row = row;
          this.dialogSearchSearch.tree.data = await this.get('/datasetImpl/' + row.id);
          for (let index in this.formDialogSearchSearch) {
            if (this.formDialogSearchSearch.hasOwnProperty(index)) {
              if (typeof row[index] !== 'undefined') {
                this.formDialogSearchSearch[index] = row[index];
              }
            }
          }
          break;
        }
        this.dialogSearchSearch.visible = true;
      },
      dialogSearchSearchSave () {
        let formRef = 'formDialogSearchSearch';
        if (this.dialogSearchSearch.title === '新增') {
          this.VALIDATE(formRef, async option => {
            if (this.dialogSearchSearch.all) {
              try {
                delete option.ids;
                option.all = true;
                option.id = this.dialogSearch.row.id;
                let {id} = await this.post('/dataset/add', option);
                option.dCreater = this.USER_user.name;
                option.id = id;
                this.tableSearch.data = [option, ...this.tableSearch.data];
                this.tableSearch.total++;
                this.dialogSearchSearchInit();
                this.dialogSearchSearch.visible = false;
              } catch (err) {
                console.log(err);
              }
            } else {
              let ids = treeIds(this.dialogSearchSearch.tree.data);
              if (ids.length === 0) {
                return this.$alert('请选择数据集内容！');
              }
              option.ids = ids;
              option.all = false;
              option.id = this.dialogSearch.row.id;
              try {
                let {id} = await this.post('/dataset/add', option);
                option.dCreater = this.USER_user.name;
                option.id = id;
                this.tableSearch.data = [option, ...this.tableSearch.data];
                this.tableSearch.total++;
                this.dialogSearchSearchInit();
                this.dialogSearchSearch.visible = false;
              } catch (err) {
                console.log(err);
              }
            }
          });
        } else if (this.dialogSearchSearch.title === '修改') {
          this.VALIDATE(formRef, async option => {
            if (this.dialogSearchSearch.all) {
              try {
                delete option.ids;
                option.all = true;
                option.id = this.dialogSearch.row.id;
                await this.post('/datasetImpl/update/' + this.dialogSearchSearch.row.id, option);
                option.dCreater = this.USER_user.name;
                this.dialogSearch.row.dName = option.dName;
                this.dialogSearchSearchInit();
                this.dialogSearchSearch.visible = false;
              } catch (err) {
                console.log(err);
              }
            } else {
              let ids = treeIds(this.dialogSearchSearch.tree.data);
              if (ids.length === 0) {
                return this.$alert('请选择数据集内容！');
              }
              option.ids = ids;
              if (option.ids.length === 0) {
                return this.$alert('请选择数据集内容！');
              }

              let add = [];
              let del = [];
              for (let item of option.ids) {
                if (this.dialogSearchSearch.idsOld.indexOf(item) === -1) {
                  add.push(item);
                }
              }
              for (let item of this.dialogSearchSearch.idsOld) {
                if (option.ids.indexOf(item) === -1) {
                  del.push(item);
                }
              }
              option.all = false;
              option.id = this.dialogSearch.row.id;
              delete option.ids;
              option.add = add;
              option.del = del;
              try {
                await this.post('/datasetImpl/update/' + this.dialogSearchSearch.row.id, option);
                option.dCreater = this.USER_user.name;
                this.dialogSearchSearch.row.dName = option.dName;
                this.dialogSearchSearchInit();
                this.dialogSearchSearch.visible = false;
              } catch (err) {
                console.log(err);
              }
            }
          });
        } else {
          this.dialogInit(formRef);
          this.dialogSearchSearch.visible = false;
        }
      },
      dialogSearchSearchOk () {
        this.dialogInit('formDialogSearchSearch');
        this.dialogSearchSearch.visible = false;
      },
      tableSearchDelete (row) {
        this.$confirm('您将删除数据集。', '确认删除？', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        })
          .then(async _ => {
            try {
              await this.post('/dataset/delete/', [row.id]);
              this.tableWatch('tableSearch');
            } catch (err) {
              console.log(err);
            }
          })
          .catch(_ => {
          });
      },
      checkAllChange () {
        this.dialogSearchSearch.isIndeterminate = false;
        let tree = this.formDialogSearchSearch.id === 0 ? 'tree0' : 'tree1';
        if (this.dialogSearchSearch.checkAll) {
          let keys = dialogSearchGetKeys(this.dialogSearchSearch.tree.data);
          this.$refs[tree].setCheckedKeys(keys);
        } else {
          this.$refs[tree].setCheckedKeys([]);
        }
      },
      checkChange (data, isTrue, hasTrue) {
        let tree = this.formDialogSearchSearch.id === 0 ? 'tree0' : 'tree1';
        if (this.$refs[tree].getCheckedKeys().length === this.dialogSearchSearch.tree.size) {
          this.dialogSearchSearch.isIndeterminate = false;
          this.dialogSearchSearch.checkAll = true;
        } else if (this.$refs[tree].getCheckedKeys().length === 0) {
          this.dialogSearchSearch.isIndeterminate = false;
          this.dialogSearchSearch.checkAll = false;
        } else if (this.dialogSearchSearch.checkAll) {
          this.dialogSearchSearch.isIndeterminate = false;
          this.dialogSearchSearch.checkAll = false;
        } else {
          this.dialogSearchSearch.isIndeterminate = true;
          this.dialogSearchSearch.checkAll = false;
        }
        if (data.once) {
          delete data.once;
          return;
        }
        if (!data.disabled) data.include = isTrue;
      },
    },
    mounted: function () {
      this.tableWatch('table');
      console.log(this);
    },
  });
  function treeFormat (tree, ids = []) {
    let formatTree = [];
    tree.forEach(item => {
      let node = {};
      node = Object.assign({}, item);
      node.include = ids.findIndex(id => { return id === node.key; }) !== -1;
      if (item.children && item.children.length > 0) {
        node.children = treeFormat(item.children, ids);
        if (node.include) {
          node.once = true;
        }
      }
      formatTree.push(node);
    });
    return formatTree;
  }
  function treeIds (tree) {
    let ids = [];
    tree.forEach(item => {
      let idsStep = [];
      if (item.children && item.children.length > 0) {
        idsStep = treeIds(item.children);
      }
      if (item.include) {
        idsStep.push(item.key);
      }
      ids = ids.concat(idsStep);
    });
    return ids;
  }
  function dialogSearchGetKeys (data) {
    let keys = [];
    data.forEach(item => {
      if (item.disabled && item.children && item.children.length > 0) {
        keys = [
          ...keys,
          ...dialogSearchGetKeys(item.children),
        ];
      } else {
        keys.push(item.key);
      }
    });
    return keys;
  }
  function dialogSearchGetSize (data) {
    let length = 0;
    data.forEach(item => {
      if (item.children && item.children.length > 0) {
        length += dialogSearchGetSize(item.children);
      }
      length++;
    });
    return length;
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss">
.is-disabled {
  display: none;
}
</style>

<style scoped lang="scss">
  .box-card {
    margin: 20px;
  }

  .createTimeSpan {
    display: block;
    margin-top: 34px;
  }

  @media screen and (max-width: 800px) {
    .createTimeSpan {
      margin-top: 0;
    }
    .box-card {
      margin: 0;
    }
  }

  .el-select {
    width: 100%;
  }
</style>
